import type { RadioGroupProps } from './types.ts'
import React, { useEffect, useState } from 'react'
import RadioGroupItem from './radio-group-item.tsx'

function uuid(): string {
  return Math.random().toString(36).substring(2)
}

const RadioGroup: React.FC<RadioGroupProps> = ({
  options,
  name = uuid(),
  type = 'button',
  defaultValue,
  isWrap = false,
  onChange = () => {},
}) => {
  const [selectedValue, setSelectedValue] = useState<string>(options?.[0]?.value || defaultValue || '')

  useEffect(() => {
    if (defaultValue) {
      setSelectedValue(defaultValue)
    }
  }, [defaultValue])

  const handleChange = (value: string) => {
    setSelectedValue(value)
    onChange(value)
  }

  const wrapClass = isWrap ? 'flex-wrap' : 'flex-nowrap overflow-x-auto '

  return (
    <div className={`w-100% flex gap-12px ${wrapClass}`}>
      {options.map((option) => {
        return (
          <RadioGroupItem
            option={option}
            key={option.value}
            checked={selectedValue === option.value}
            name={name}
            type={type}
            onChange={handleChange}
          />
        )
      })}
    </div>
  )
}

RadioGroup.displayName = 'RadioGroup'
export default RadioGroup
